package com.vhly.apb;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SimpleCursorAdapter;
import com.vhly.remoteapi.yahoo.contact.Contact;
import com.vhly.remoteapi.yahoo.contact.ContactObject;
import org.scribe.model.Token;
import org.scribe.oauth.OAuthService;

import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 2010-12-12
 * Time: 20:26:20
 * Email: vhly@163.com
 */
public class MainActivity extends ListActivity implements ClientHandler, Runnable, DialogInterface.OnClickListener {

    private APBYahooClient yahooClient;

    private AlertDialog dialog;

    private SimpleCursorAdapter adapter;

    private ProgressDialog progress;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        Cursor peopleCursor = loadDeviceContacts();

        Cursor peopleCursor = ContactSyncStore.getInstance().getContacts();

//        adapter = new SimpleCursorAdapter(this, R.layout.main, peopleCursor, new String[]{Contacts.People.DISPLAY_NAME, Contacts.People.NUMBER}, new int[]{R.id.txtname, R.id.txtnumber});
        adapter = new SimpleCursorAdapter(this, R.layout.main, peopleCursor, new String[]{"CNAME", "CNUMBER"}, new int[]{R.id.txtname, R.id.txtnumber});


        setListAdapter(adapter);

        if (yahooClient == null) {
            yahooClient = new APBYahooClient(this.getApplicationContext());
        }
        Log.d("MainActivity", "onCreate");
        boolean bok = yahooClient.loadToken();
        if (!bok) {
            if (dialog == null) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                dialog = builder.create();
            }
            dialog.setTitle(R.string.comfirm);
            dialog.setMessage(getString(R.string.needauth));
            dialog.setButton(getString(R.string.ok), this);
            dialog.setButton2(getString(R.string.cancel), this);
            dialog.show();
        } else {
            bok = yahooClient.accessTokenIsExpired();
            if (bok) {
                Thread thd = new Thread(this);
                thd.start();
            }
        }

    }

    /**
     * Load Device's Contacts.
     *
     * @return Cursor
     */
    public Cursor loadDeviceContacts() {
        String[] projection = new String[]{
                Contacts.People._ID,
                Contacts.People.NAME,
                Contacts.People.NUMBER,
        };
        Uri contactUri = Contacts.People.CONTENT_URI;

        // Best way to retrieve a query; returns a managed query.
        Cursor peopleCursor = managedQuery(contactUri,
                /*projection*/null, //Which columns to return.
                null, // WHERE clause--we won't specify.
                null, // Selection Args??
                Contacts.People.DEFAULT_SORT_ORDER); // Order-by name

        // go to the beginning of the list
        boolean bn = peopleCursor.moveToFirst();
        Vector<Contact> cts = new Vector<Contact>();
        while (bn) {
            cts.add(ContactCursorParser.parse(peopleCursor));
            bn = peopleCursor.moveToNext();
        }
        System.out.println("cts.size() = " + cts.size());
        return peopleCursor;
    }

    @Override
    protected void onStop() {
        if (yahooClient != null) {
            yahooClient.saveToken();
        }
        super.onStop();
    }

    public void onClick(DialogInterface dialogInterface, int which) {
        switch (which) {
            case Dialog.BUTTON1:
                // TODO Auth
                ClientAsyncTask task = new ClientAsyncTask();
                task.handler = this;
                task.execute((String[]) null);
                break;
            case Dialog.BUTTON2:
                // TODO Cancel
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            String vc = data.getExtras().getString("verifyCode");
            System.out.println("vc = " + vc);
            ClientAsyncTask task = new ClientAsyncTask();
            task.handler = this;
            task.execute(vc);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.mnu_sync:
                // TODO Download contact from yahoo
                boolean bok = yahooClient.isAuthorization();
                if (bok) {
//                    String guid = yahooClient.getMeGUID();
//                    System.out.println("guid = " + guid);
                    ContactSyncStore store = ContactSyncStore.getInstance();
                    String contactSync = yahooClient.getContactSync(yahooClient.getGUID(), store.getClientRev());
                    Vector<ContactObject> cos = store.parseSync(contactSync);
                    if (cos != null && cos.size() > 0) {
                        int synced = store.updateStore(cos);
                        System.out.println("synced = " + synced);
                        if (synced > 0) {
                            // TODO Alert Sync ed number.
                            Cursor cursor = store.getContacts();
                            adapter.changeCursor(cursor);
                            adapter.notifyDataSetChanged();
                        }
                    }
                } else {
                    if (dialog == null) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        dialog = builder.create();
                    }
                    dialog.setTitle(R.string.comfirm);
                    dialog.setMessage(getString(R.string.needauth));
                    dialog.setButton(getString(R.string.ok), this);
                    dialog.setButton2(getString(R.string.cancel), this);
                    dialog.show();
                }
                break;
            case R.id.mnu_setting:
                Intent setting = new Intent(this, SettingActivity.class);
                startActivity(setting);
                break;
        }

        return true;
    }

    public Object execTask(Object[] objects) {
        Object ret;
        OAuthService oauth = yahooClient.getOAuthService();
        if (oauth != null) {
            if (objects == null) {
                Token token = null;
                try {
                    token = yahooClient.getRequestTokenFromServ();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (token != null && token.getToken() != null) {
                    ret = token.getOther("xoauth_request_auth_url");
                    if (ret == null) {
                        StringBuffer sb = new StringBuffer("https://api.login.yahoo.com/oauth/v2/request_auth?oauth_token=");
                        sb.append(token.getToken());
                        ret = sb.toString();
                    }
                } else {
                    ret = null;
                }
            } else {
                ret = null;
                int len = objects.length;
                if (len == 1) {
                    Object obj = objects[0];
                    if (obj instanceof String) {
                        String vc = (String) obj;
                        Token token = yahooClient.getAccessTokenFromServ(vc);
                        if (token != null) {
                            yahooClient.saveToken();
                            System.out.println("token = " + token);
                        }
                    }
                }
            }
        } else {
            ret = null;
        }
        return ret;
    }

    public void taskFinished(Object result) {
        if (result != null) {
            if (result instanceof String) {
                String rau = (String) result;
                Intent rain = new Intent(this, AuthorizeActivity.class);
                rain.putExtra("rau", rau);
                startActivityForResult(rain, 1);
            }
        }
    }

    public void run() {
        // TOKEN expired
        Token token;
        try {
            token = yahooClient.refreshAccessToken();
            if (token != null && token.getToken() != null) {
                yahooClient.saveToken();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
